package com.wufun.overseas.view.lib;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * Created by xiet on 2015/7/7.
 */
public class ImageScaner {
    private final String TAG = getClass().getSimpleName();
    private static ImageScaner instance;
    private final Context mContext;

    private static final int SCAN_IMAGE = 0x00;
    private static final int SCANING_IMAGE = 0x02;
    private static final int SCAN_FOLDER = 0x04;
    private static final int SCANING_FOLDER = 0x08;
    /**
     * ��ʱ�ĸ����࣬���ڷ�ֹͬһ���ļ��еĶ��ɨ��
     */
    private HashSet<String> mDirPaths = new HashSet<String>();

    /**
     * ɨ���õ����е�ͼƬ�ļ���
     */
    private List<ImageFolder> mImageFloders = new ArrayList<ImageFolder>();
    int totalCount = 0;

    private boolean showProgress = false;

    private ProgressDialog mProgressDialog;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            if (mOnImageScanListener == null) return;
            switch (msg.what) {
                case SCAN_FOLDER:
                    mOnImageScanListener.onScanEnd(mImageFloders);

                    if (totalCount == 0 && showProgress)
                        Toast.makeText(mContext, "没扫描到一张图片", Toast.LENGTH_SHORT).show();
                    break;
                case SCAN_IMAGE:
                    mOnImageScanListener.onScanEnd(msg.obj);
                    break;
                case SCANING_IMAGE:
                    mOnImageScanListener.onScaning(msg.obj);
                    break;
                case SCANING_FOLDER:
                    mOnImageScanListener.onScaning(msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    private OnImageScanListener mOnImageScanListener;

    public void setOnImageScanListener(OnImageScanListener l) {
        this.mOnImageScanListener = l;
    }

    public interface OnImageScanListener {
        void onScanStart();

        void onScaning(Object item);

        void onScanEnd(Object result);
    }

    public ImageScaner(Context context) {
        this.mContext = context;
    }

    public static ImageScaner getInstance(Context context) {
        if (instance == null)
            synchronized (ImageScaner.class) {
                instance = new ImageScaner(context);
            }

        return instance;
    }

    /**
     * ����ContentProviderɨ���ֻ��е�ͼƬ���˷��������������߳��� ���ͼƬ��ɨ��
     */
    public synchronized void scan() {
        if (this.mContext == null) {
            Log.e(TAG, "scan failed...");
            return;
        }

        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(mContext, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }

        // ��ʾ������
        if (showProgress)
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载...");
        if (mOnImageScanListener != null)
            mOnImageScanListener.onScanStart();

        new Thread(new Runnable() {
            @Override
            public void run() {

                String firstImage = null;

                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = mContext.getContentResolver();

                // ֻ��ѯjpeg��png��ͼƬ
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"},
                        MediaStore.Images.Media.DATE_MODIFIED);
                if (mCursor==null)return;
                while (mCursor.moveToNext()) {
                    // ��ȡͼƬ��·��
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));

                    // �õ���һ��ͼƬ��·��
                    if (firstImage == null)
                        firstImage = path;
                    // ��ȡ��ͼƬ�ĸ�·����
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    ImageFolder imageFloder = null;
                    // ����һ��HashSet��ֹ���ɨ��ͬһ���ļ��У���������жϣ�ͼƬ�����������൱�ֲ���~~��
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        // ��ʼ��imageFloder
                        imageFloder = new ImageFolder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }

                    if (parentFile.list(getPicFlieFilter()) == null) continue;
                    int picSize = parentFile.list(getPicFlieFilter()).length;
                    totalCount += picSize;

                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);

                    Message msg = mHandler.obtainMessage();
                    msg.what = SCANING_FOLDER;
                    msg.obj = imageFloder;
                    mHandler.sendMessage(msg);
                }
                mCursor.close();

                // ɨ����ɣ�������HashSetҲ�Ϳ����ͷ��ڴ���
                mDirPaths = null;

                // ֪ͨHandlerɨ��ͼƬ���
//                mHandler.sendEmptyMessage(SCAN_FOLDER);
                Message msg = mHandler.obtainMessage();
                msg.what = SCAN_FOLDER;
                msg.obj = mImageFloders;
                mHandler.sendMessage(msg);


            }
        }).start();
    }

    public List<String> scanDir(String dir) {
        List<String> ret = new ArrayList<String>();
        if (dir != null && !dir.equals(""))
            ret = Arrays.asList(new File(dir).list(getPicFlieFilter()));

        return ret;
    }

    /**
     * ��ȡĳһ·����ͼƬ�б�
     *
     * @param dir
     * @return
     */
    public synchronized void scan(String dir) {
        if (mOnImageScanListener != null)
            mOnImageScanListener.onScanStart();
        if (dir != null && !dir.equals("")) {
            List<String> ret = new ArrayList<String>();
            ret = Arrays.asList(new File(dir).list(getPicFlieFilter()));

            Message msg = mHandler.obtainMessage();
            msg.what = SCAN_IMAGE;
            msg.obj = ret;
            mHandler.sendMessage(msg);
        } else {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    List<String> ret = new ArrayList<String>();
                    Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    ContentResolver mContentResolver = mContext.getContentResolver();

                    // ֻ��ѯjpeg��png��ͼƬ
                    Cursor mCursor = mContentResolver.query(mImageUri, null,
                            MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                            new String[]{"image/jpeg", "image/png"},
                            MediaStore.Images.Media.DATE_MODIFIED);

                    while (mCursor.moveToNext()) {
                        // ��ȡͼƬ��·��
                        String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));

                        Message msg = mHandler.obtainMessage();
                        msg.what = SCANING_IMAGE;
                        msg.obj = path;
                        mHandler.sendMessage(msg);

                        ret.add(path);
                    }
                    mCursor.close();

                    Message msg = mHandler.obtainMessage();
                    msg.what = SCAN_IMAGE;
                    msg.obj = ret;
                    mHandler.sendMessage(msg);
                }
            }.start();
        }
    }

    private FilenameFilter getPicFlieFilter() {
        return new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                return filename.endsWith(".jpg")
                        || filename.endsWith(".png")
                        || filename.endsWith(".jpeg");
            }
        };
    }
}
